<template>
  <div class="drag" ref="dragDiv">
    {{ msg }}
    <div
      class="block"
      :class="{ block_ok_bg: is_success }"
      ref="moveDiv"
      @touchstart.prevent="touchstart($event)"
      @touchend.prevent="touchend($event)"
      @touchmove.prevent="touchmove($event)"
      @click=""
    ></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
const emits = defineEmits(["unlock"]);
const dragDiv = ref(null);
const moveDiv = ref(null);
let msg = ref("请滑动解锁");
let maxWidth = "";
let Xstart = 0;
let is_success = ref(false);

onMounted(() => {
  maxWidth = dragDiv.value.clientWidth - moveDiv.value.clientWidth;
});

const touchstart = (e) => {
  if (!is_success.value) {
    Xstart = e.touches[0].clientX;
  }
};
const touchmove = (e) => {
  if (!is_success.value) {
    let Xmove = e.changedTouches[0].clientX;
    if (Xmove - Xstart < maxWidth) {
      // 没到头，可以继续滑动
      moveDiv.value.style.left = Xmove - Xstart + "px";
    } else {
      moveDiv.value.style.left = maxWidth + "px";
    }
  }
};
const touchend = (e) => {
  if (!is_success.value) {
    if (e.changedTouches[0].clientX - Xstart < maxWidth) {
      moveDiv.value.style.left = "0px";
    } else {
      msg.value = "解锁成功";
      is_success.value = true;
      emits("unlock");
    }
  }
};
</script>

<style lang="scss" scoped>
.drag {
  position: relative;
  background: lightgray;
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  border-radius: 8px;
  .block {
    width: 60px;
    height: 40px;
    border-radius: 8px;
    cursor: move;
    position: absolute;
    top: 0;
    left: 0;
    background: gray url("../assets/image/slideBlock.png") no-repeat center;
    background-size: 20px 20px;
  }
  .block_ok_bg {
    background-image: url("../assets/image/success.png");
  }
}
</style>